package zx.lrn.notes.basic_grammer.about_collections;

import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @ClassName: ConcurrentHashMapDemo
 * @Description: 并发安全集合-ConcurrentHashMap
 * @Author: zhaoxuan
 * @Date: 2020/3/11 0:03
 **/
public class ConcurrentHashMapDemo {
    private static Map<String, Integer> map = new ConcurrentHashMap();

    /**
     * 统计一下目录中所有文本中的所有行出现的次数
     * 
     * @param args
     */
    public static void main(String[] args) throws Exception {
        URL txtsUrl = ConcurrentHashMapDemo.class.getResource("/txt_sources");
        Path start = new File(txtsUrl.toURI()).toPath();
        ExecutorService pool = Executors.newCachedThreadPool();

        List<Callable<Integer>> allSearchers = Files.walk(start).filter(path -> !Files.isDirectory(path))
            .map(ConcurrentHashMapDemo::buildSearchMission).collect(Collectors.toList());
        pool.invokeAll(allSearchers);
        pool.shutdown();
        System.out.println(map);
    }

    private static Callable<Integer> buildSearchMission(Path path) {
        return () -> {
            Files.lines(path).forEach(line -> {
                map.merge(line, 1, (a, b) -> a + b);
            });
            return 1;
        };
    }
}
